package com.hnevc.androidui11;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String json1 = "{\"name\":\"zhangsan\",\"age\":27,\"married\":true}";
        //创建解析对象
        Gson gson = new Gson();

        //完成解析
        Person person = gson.fromJson(json1, Person.class);
        //验证是否已经验证成功
        Toast.makeText(this, person.getName(), Toast.LENGTH_SHORT).show();

        String json2 = "[12,35,64]";
        //创建一个数组类型符号
        Type listType = new TypeToken<List<Integer>>() {
        }.getType();
        //完成解析
        List<Integer> integerList = gson.fromJson(json2, listType);
        Toast.makeText(this, integerList.get(1) + "", Toast.LENGTH_SHORT).show();


        String json3 = "[\"12\",\"35\",\"64\"]";
        //创建一个数组类型符号
        listType = new TypeToken<List<String>>() {
        }.getType();
        //完成解析
        List<String> stringList = gson.fromJson(json3, listType);
        Toast.makeText(this, stringList.get(2) + "", Toast.LENGTH_SHORT).show();


        //读取weather.json的内容到字符串
        String json4 = "";
        InputStream inputStream = getResources().openRawResource(R.raw.weather2);
//定义缓存
        try {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            //buffer中就是文件中的数据的字节数据,将buffer装换为字符串
            json4 = new String(buffer);
            listType = new TypeToken<List<Weather>>() {
            }.getType();
            //解析完成了
            List<Weather> weatherList = gson.fromJson(json4, listType);
            Toast.makeText(this, weatherList.get(1).getWeather(), Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
        }

        SharedPreferences sp = getSharedPreferences("cookie",MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("username","黄顶");
        edit.putString("password","123");
        edit.commit();


        SharedPreferences sp1 = getSharedPreferences("cookie",MODE_PRIVATE);
        String username =  sp1.getString("username","未命名");
        Toast.makeText(this, username, Toast.LENGTH_SHORT).show();

        //获取listview视图控件
        ListView mListView = findViewById(R.id.lv_numbers);
        //创建MYZBaAdapter对象
        MybaseAdapter adapter = new MybaseAdapter(this);
        //将MYZBaAdapter对象，绑定到ListView控件
        mListView.setAdapter(adapter);
    }
}
